from typing import List, Dict


class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        if len(fruits) <= 2:
            return len(fruits)

        ret, left, right = 0, 0, 0
        cnt_map = {fruits[0]: 1}
        while right + 1 < len(fruits):
            while not self.can_append(fruits[right + 1], cnt_map):
                if fruits[left] in cnt_map:
                    cnt_map[fruits[left]] -= 1
                    if cnt_map[fruits[left]] == 0:
                        cnt_map.pop(fruits[left])
                left += 1
            if fruits[right + 1] in cnt_map:
                cnt_map[fruits[right + 1]] += 1
            else:
                cnt_map[fruits[right + 1]] = 1
            right += 1
            ret = max(ret, right - left + 1)
        return ret

    def can_append(self, num: int, cnt_map: Dict[int, int]) -> int:
        if len(cnt_map) <= 2 and num in cnt_map:
            return True
        if len(cnt_map) < 2 and num not in cnt_map:
            return True
        return False
